import { parse } from 'qs'
import { message } from 'antd'
import { isEmpty, cloneDeep } from 'lodash'
import config from '../../../../config/config'
import { Link, hashHistory } from 'dva/router'
import {
	updateStatus,
	batchDelete,
	batchUpdate,
	getOrganize,
	getDuty,
	search,
	createCustomer,
	roleList,
	update,
    getroleList,
} from './userListServ'

// 初始默认状态
const defaultState = {
	biz: {
		queryForm: {}
	},
    roleList: [],
	organizeList: [],
	dutyList: [],
	// 弹出框操作类型 -- delete：批量删除；forbid：批量禁用；open：批量启用
	modalType: '',
	//显示新增
	showAddVisible: false,
	// 弹出框显示状态
	showDetailModal: false,
	// 保存操作状态
	btnLoading: false,
	modalPageData: {
		pageSize: 10,
		pageNo: 1
	},
	allRoleList: [
		{ id: 1, name: '管理员1' },
		{ id: 2, name: '管理员2' },
		{ id: 3, name: '管理员3' },
		{ id: 4, name: '管理员4' },
		{ id: 5, name: '管理员5' }
	],
	dataSource: [],
	actionType: '',
	detailData: {}
};

const tmpModule = {
	state: defaultState,
	//订阅数据
	subscriptions: {
		setup({ dispatch, history }) {
			return history.listen(location => {
				if (location.pathname == tmpModule.pathname) {
					dispatch({ type: 'roleList', payload: { status: 0, pageSize: 1000 } })
                    dispatch({ type: 'fetchRoleList', payload: { pageSize: 1000} })
				}
			})
		},
	},
	//数据逻辑部分
	effects: {
		*init({ payload }, { put, call, select }) {
			yield put({ type: 'getOrganize' });
			if (config.appId == 3) {
				yield put({ type: 'getDuty' });
			}
		},

		// 设置表单的值到状态机
		*setFormVal({ payload }, { put, call, select }) {
			let { biz } = yield select(d => d[tmpModule.namespace])
			try {
				yield put({
					type: 'updateStore',
					payload: {
						biz: payload
					}
				})
			} catch (e) {
				console.error(e)
			}
		},

		*getFrom4AUser({ payload }, { put, call, select }) {
			let { detailData, dataSource } = yield select(d => d[tmpModule.namespace])
			try {
				let { data, success } = yield call(search, parse(payload));
				// debugger
				if (success) {
					data && data.map((item, i) => {
						item["checked"] = false
						item['key'] = i + 1
					})
					dataSource = data
					yield put({
						type: 'updateStore',
						payload: { dataSource }
					})
				}
			} catch (e) {
				console.error(e)
			}
		},

		//启用禁用
		*changeStatus({ payload }, { put, call, select }) {
			try {
				let { success } = yield call(updateStatus, payload.params);
				if (success) {
					message.success('操作成功');
					payload.cb();
				}
			} catch (e) {
				console.error(e)
			}
		},

		//批量删除
		*batchDelete({ payload }, { put, call, select }) {
			yield put({ type: 'updateStore', payload: { btnLoading: true } });

			try {
				let { data, resultCode } = yield call(batchDelete, payload.params);
				if (resultCode == 0) {
					message.success('操作成功');
					yield put({ type: 'updateStore', payload: { showDetailModal: false } });
					payload.cb();
				}
			} catch (e) {
				console.error(e)
			}

			yield put({ type: 'updateStore', payload: { btnLoading: false } });
		},

		//批量更新状态
		*batchUpdate({ payload }, { put, call, select }) {
			yield put({ type: 'updateStore', payload: { btnLoading: true } });
			try {
				let { data, msg,success } = yield call(batchUpdate, payload.params);
				if (success) {
					message.success('操作成功');
					yield put({ type: 'updateStore', payload: { showDetailModal: false } });
					payload.cb();
				}
			} catch (e) {
				console.error(e)
			}

			yield put({ type: 'updateStore', payload: { btnLoading: false } });
		},
		*createCustomer({ payload }, { put, call, select }) {
			try {
				let { data, msg,success } = yield call(createCustomer, parse(payload));
				let {accountId}=data
				if (success) {
					message.success('新增成功');
					hashHistory.push({
						pathname: '/home/backStageAdmin/userEdit',
						query: {accountId}
					});
					yield put({ type: 'updateStore', payload: { showAddVisible: false, } });
				}
			} catch (e) {
				console.error(e)
			}
			yield put({ type: 'updateStore', payload: { btnLoading: false } });
		},
		*roleList({ payload }, { put, call, select }) {
			try {
				let { rows=[], success } = yield call(roleList, parse(payload));
				if (success) {
					// message.success('新增成功');
					yield put({ type: 'updateStore', payload: { allRoleList: rows } });
				}
			} catch (e) {
				console.error(e)
			}
			yield put({ type: 'updateStore', payload: {} });
		},
		*update({ payload }, { put, call, select }) {
			try {
				let { success } = yield call(update, parse(payload));
				if (success) {
					message.success('更新成功');
					payload.cb();
				}
			} catch (e) {
				console.error(e)
			}
			yield put({ type: 'updateStore', payload: { showAddVisible: false } });
		},
		// //批量更新状态
		// *onSearch({ payload }, { put, call, select }) {
		//     let { detailData } = yield select(d => d[tmpModule.namespace])
		//     try {
		//         let { data, resultCode } = yield call(search, parse({detailData}));
		//         if (resultCode == 0) {
		//             yield put({ type: 'updateStore', payload: { showDetailModal: false } });
		//             payload.cb();
		//         }
		//     } catch (e) {
		//         console.error(e)
		//     }
		// },
        *fetchRoleList({ payload }, { put, call, select }) {
            // let { roleList } = yield select(d => d[tmpModule.namespace])
            try {
                let { data, success } = yield call(getroleList, parse(payload));
                if (success) {
                    // message.success('新增成功');
                    let arr = (data instanceof Array) ? arr = data.map(item => {
                        return { value: item.permissionRoleId, label: item.name }
                    }) : []

                    yield put({ type: 'updateStore', payload: { roleList: arr } });
                }
            } catch (e) {
                console.error(e)
            }
            yield put({ type: 'updateStore', payload: {} });
        },

	},
	//更新数据到state
	reducers: {
		updateStore(preState, action) {
			return Object.assign({}, preState, action.payload);
		}
	}
}
export default tmpModule
